<template>
  <div class="a3-container">
    <div class="header">
      <h1><el-icon><Document /></el-icon> A3用户界面</h1>
      <div class="user-info">
        <el-icon><User /></el-icon>
        <span class="welcome">欢迎，</span>
        <span class="username">{{ username }}</span>
        <el-button class="logout-btn" @click="handleLogout" type="danger">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </div>
    
    <div class="main-content" :class="{ 'full-width': !currentPdf }">
      <!-- PDF预览部分 -->
      <div class="section pdf-section" :class="{ 'full-width': !currentPdf }">
        <h2>PDF文件预览</h2>
        <div class="pdf-list" v-if="pdfList.length > 0">
          <div v-for="item in pdfList" 
               :key="item.id" 
               :class="['pdf-item', { active: currentPdf?.id === item.id }]">
            <div class="pdf-info" @click="selectPdf(item)">
              <span class="pdf-name">{{ item.fileName }}</span>
              <span class="pdf-time">上传时间：{{ new Date(item.uploadTime).toLocaleString('zh-CN', { 
                year: 'numeric', 
                month: '2-digit', 
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false 
              }) }}</span>
            </div>
            <div class="pdf-actions">
              <el-button 
                type="primary" 
                size="small" 
                @click.stop="downloadPdf(item)"
                :loading="item.downloading">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </div>
          </div>
        </div>
        <div v-else class="no-data">暂无待审核的PDF文件</div>
      </div>

      <!-- QA对审核部分 -->
      <div class="section qa-section" v-if="currentPdf">
        <div class="section-header">
          <h2>问答对审核</h2>
          <div class="header-actions">
            <el-button 
              type="success" 
              @click="saveAllChanges"
              :disabled="!hasChanges">
              提交
            </el-button>
          </div>
        </div>

        <div class="qa-list" v-if="qaList.length > 0">
          <div class="qa-navigation">
            <span class="qa-counter">问答对 {{ currentPage }}/{{ qaList.length }}</span>
          </div>
          <div :class="['qa-item', { 'qa-item-approved': currentQa.status === 'approved', 'qa-item-rejected': currentQa.status === 'rejected' }]">
            <div class="qa-header">
              <span class="qa-index">问答对 #{{ currentPage }}</span>
              <div class="qa-status" v-if="currentQa.status">
                <el-tag :type="currentQa.status === 'approved' ? 'success' : 'danger'">
                  {{ currentQa.status }}
                </el-tag>
              </div>
            </div>
            <div class="qa-content">
              <div class="qa-field">
                <label>问题：</label>
                <div class="qa-text" v-if="!currentQa.editing">{{ currentQa.instruction }}</div>
                <el-input
                  v-else
                  v-model="currentQa.instruction"
                  type="textarea"
                  rows="3"
                  placeholder="请输入问题"
                />
              </div>
              <div class="qa-field">
                <label>答案：</label>
                <div class="qa-text" v-if="!currentQa.editing">{{ currentQa.output }}</div>
                <el-input
                  v-else
                  v-model="currentQa.output"
                  type="textarea"
                  rows="5"
                  placeholder="请输入答案"
                />
              </div>
              <div class="qa-actions">
                <div class="qa-edit-actions" v-if="currentQa.editing">
                  <el-button type="primary" @click="confirmEdit(currentPage - 1)">确认</el-button>
                  <el-button @click="cancelEdit(currentPage - 1)">取消</el-button>
                </div>
                <div class="qa-review-actions" v-else>
                  <el-button type="primary" @click="editQa(currentPage - 1)" 
                    :disabled="currentQa.statusCode === 2 || currentQa.statusCode === 3">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button 
                    :type="currentQa.status === 'approved' ? 'info' : 'success'"
                    @click="currentQa.status === 'approved' ? cancelApprove(currentPage - 1) : approveQa(currentPage - 1)"
                    :disabled="currentQa.status === 'rejected'">
                    <el-icon><Check /></el-icon>
                    {{ currentQa.status === 'approved' ? '取消通过' : '通过' }}
                  </el-button>
                  <el-button 
                    :type="currentQa.status === 'rejected' ? 'info' : 'danger'"
                    @click="currentQa.status === 'rejected' ? cancelReject(currentPage - 1) : rejectQa(currentPage - 1)"
                    :disabled="currentQa.status === 'approved'">
                    <el-icon><Close /></el-icon>
                    {{ currentQa.status === 'rejected' ? '取消驳回' : '驳回' }}
                  </el-button>
                </div>
              </div>
              <div class="qa-feedback" v-if="currentQa.feedback">
                <label>驳回原因：</label>
                <div class="feedback-text">{{ currentQa.feedback }}</div>
              </div>
            </div>
          </div>
          <div class="qa-navigation-buttons">
            <el-button 
              :disabled="currentPage === 1"
              @click="currentPage--"
              type="primary"
              plain>
              <el-icon><ArrowLeft /></el-icon>
              上一个
            </el-button>
            <el-button 
              :disabled="currentPage === qaList.length"
              @click="currentPage++"
              type="primary"
              plain>
              <el-icon><ArrowRight /></el-icon>
              下一个
            </el-button>
          </div>
        </div>
        <div v-else class="no-data">当前PDF文件暂无问答对</div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Download, Edit, Check, Close, ArrowLeft, ArrowRight, Document, User, SwitchButton } from '@element-plus/icons-vue';
import request from '@/utils/request';
import axios from 'axios';

export default {
  name: 'A3Main',
  components: {
    Download,
    Edit,
    Check,
    Close,
    ArrowLeft,
    ArrowRight,
    Document,
    User,
    SwitchButton
  },
  setup() {
    const router = useRouter();
    const username = ref('');
    const pdfList = ref([]);
    const currentPdf = ref(null);
    const qaList = ref([]);
    const originalQaList = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const qaStatusList = ref([]);

    // 计算是否有更改
    const hasChanges = computed(() => {
      return qaStatusList.value.length > 0;
    });

    // 计算当前显示的QA对
    const currentQa = computed(() => {
      return qaList.value[currentPage.value - 1] || {};
    });

    // 获取PDF列表
    const fetchPdfList = async () => {
      try {
        loading.value = true;
        const response = await request.get('http://10.137.10.169:8080/api/me/reviewTask/file');
        console.log("返回的数据", response.data);
        
        if (response.data.code === 200) {
          // 获取每个文件的详细信息
          const fileDetails = await Promise.all(
            response.data['computer-view'].map(async (item) => {
              try {
                const detailResponse = await request.get(`http://localhost:8080/api/file/info/${item.fileId}`);
                if (detailResponse.data.code === 200) {
                  return {
                    ...item,
                    fileName: detailResponse.data.data.fileName,
                    uploadTime: detailResponse.data.data.uploadTime,
                    downloading: false
                  };
                }
                return {
                  ...item,
                  fileName: `文件${item.fileId}`,
                  uploadTime: new Date().toISOString(),
                  downloading: false
                };
              } catch (error) {
                console.error(`获取文件${item.fileId}详情失败:`, error);
                return {
                  ...item,
                  fileName: `文件${item.fileId}`,
                  uploadTime: new Date().toISOString(),
                  downloading: false
                };
              }
            })
          );
          
          pdfList.value = fileDetails;
        } else {
          throw new Error(response.data.msg || '获取PDF列表失败');
        }
      } catch (error) {
        console.error('获取PDF列表失败:', error);
        ElMessage.error('获取PDF列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0:
          return null; // 初始状态，不显示任何状态
        case 1:
          return '等待审核';
        case 2:
          return '计算机老师审核通过';
        case 3:
          return '计算机老师审核不通过';
        case 4:
          return '最后审核通过';
        case 5:
          return '最后审核不通过';
        case 6:
          return '被标记';
        default:
          return null; // 默认状态，不显示任何状态
      }
    };

    // 获取状态类型（用于标签颜色）
    const getStatusType = (status) => {
      switch (status) {
        case 1:
          return 'info';
        case 2:
          return 'success';
        case 3:
          return 'danger';
        case 4:
          return 'success';
        case 5:
          return 'danger';
        case 6:
          return 'warning';
        default:
          return 'info';
      }
    };

    // 获取QA列表
    const fetchQaList = async (pdfId) => {
      try {
        loading.value = true;
        
        const response = await request.get(`http://10.137.10.169:8080/api/me/reviewTask/qa/${pdfId}`);
        console.log("请求的文件id：", pdfId);
        console.log("问答对数据：", response.data);
        
        if (response.data.code === 200) {
          const qaData = response.data['qa-view-computer'] || [];
          
          qaList.value = qaData.map(qa => ({
            ...qa,
            editing: false,
            status: getStatusText(qa.status),
            statusCode: qa.status,
            feedback: qa.feedback || ''
          }));
          
          originalQaList.value = JSON.parse(JSON.stringify(qaList.value));
          qaStatusList.value = []; // 重置状态列表
          currentPage.value = 1;
        } else {
          qaList.value = [];
          originalQaList.value = [];
          qaStatusList.value = [];
          throw new Error(response.data.msg || '获取问答对数据失败');
        }
      } catch (error) {
        console.error('获取问答对列表失败:', error);
        ElMessage.error('获取问答对列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 选择PDF
    const selectPdf = async (pdf) => {
      if (hasChanges.value) {
        const confirm = window.confirm('有未保存的更改，是否继续？');
        if (!confirm) return;
      }
      currentPdf.value = pdf;
      currentPage.value = 1;
      await fetchQaList(pdf.id);
    };

    // 通过问答对
    const approveQa = async (index) => {
      try {
        const qa = qaList.value[index];
        qa.status = 'approved';
        qa.feedback = '';
        
        // 更新状态列表
        const existingIndex = qaStatusList.value.findIndex(item => item.id === qa.id);
        if (existingIndex !== -1) {
          qaStatusList.value[existingIndex].status = 1;
        } else {
          qaStatusList.value.push({
            id: qa.id,
            status: 1
          });
        }
        
        ElMessage.success('审核通过成功');
      } catch (error) {
        console.error('审核通过失败:', error);
        ElMessage.error('审核通过失败');
      }
    };

    // 驳回问答对
    const rejectQa = async (index) => {
      try {
        const qa = qaList.value[index];
        qa.status = 'rejected';
        qa.feedback = '';
        
        // 更新状态列表
        const existingIndex = qaStatusList.value.findIndex(item => item.id === qa.id);
        if (existingIndex !== -1) {
          qaStatusList.value[existingIndex].status = 2;
        } else {
          qaStatusList.value.push({
            id: qa.id,
            status: 2
          });
        }
        
        ElMessage.success('驳回成功');
      } catch (error) {
        console.error('驳回失败:', error);
        ElMessage.error('驳回失败');
      }
    };

    // 取消通过
    const cancelApprove = async (index) => {
      try {
        const qa = qaList.value[index];
        qa.status = null;
        qa.feedback = '';
        
        // 从状态列表中移除
        qaStatusList.value = qaStatusList.value.filter(item => item.id !== qa.id);
        
        ElMessage.success('已取消通过');
      } catch (error) {
        console.error('取消通过失败:', error);
        ElMessage.error('取消通过失败');
      }
    };

    // 取消驳回
    const cancelReject = async (index) => {
      try {
        const qa = qaList.value[index];
        qa.status = null;
        qa.feedback = '';
        
        // 从状态列表中移除
        qaStatusList.value = qaStatusList.value.filter(item => item.id !== qa.id);
        
        ElMessage.success('已取消驳回');
      } catch (error) {
        console.error('取消驳回失败:', error);
        ElMessage.error('取消驳回失败');
      }
    };

    // 编辑问答对
    const editQa = (index) => {
      if (qaList.value[index].statusCode === 2 || qaList.value[index].statusCode === 3) {
        ElMessage.warning('已审核的问答对不能编辑');
        return;
      }
      qaList.value[index].editing = true;
    };

    // 确认编辑
    const confirmEdit = async (index) => {
      try {
        const qa = qaList.value[index];
        const currentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
        
        const requestData = {
          output: qa.output,
          input: "",
          system: "",
          instruction: qa.instruction,
          creatorId: 0,
          id: qa.id,
          fileId: currentPdf.value.id,
          status: qa.statusCode || 0
        };

        console.log("更新QA对的数据：", requestData);
        const response = await request.post('http://localhost:8080/api/update/qa', requestData);
        
        if (response.data.code === 200) {
          ElMessage.success('更新成功');
          qa.editing = false;
          // 更新原始数据
          originalQaList.value[index] = { ...qa };
        } else {
          throw new Error(response.data.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新失败:', error);
        ElMessage.error('更新失败');
      }
    };

    // 取消编辑
    const cancelEdit = (index) => {
      const originalQa = originalQaList.value[index];
      qaList.value[index] = { ...originalQa, editing: false };
    };

    // 保存所有更改
    const saveAllChanges = async () => {
      try {
        loading.value = true;
        // 构造状态列表
        const statusList = qaStatusList.value.map(item => ({
          id: item.id,
          status: item.status
        }));

        console.log("请求的数据：", statusList);
        const response = await request.post('http://localhost:8080/api/view/qa/computer', statusList);
        
        if (response.data.code === 200) {
          ElMessage.success('提交成功');
          // 清空状态列表
          qaStatusList.value = [];
          // 重新获取QA列表和PDF列表
          await Promise.all([
            fetchQaList(currentPdf.value.id),
            fetchPdfList()
          ]);
        } else {
          throw new Error(response.data.msg || '提交失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      } finally {
        loading.value = false;
      }
    };

    // 下载PDF文件
    const downloadPdf = async (pdf) => {
      if (!pdf.downloading) {
        pdf.downloading = true;
        try {
          const response = await request({
            url: `http://10.137.10.169:8080/api/file/download/${pdf.fileId}`,
            method: 'GET',
            responseType: 'blob'
          });
          
          // 创建下载链接
          const blob = new Blob([response.data], { type: 'application/pdf' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = pdf.articleTitle || `文件_${pdf.fileId}.pdf`;
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          
          // 清理
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          ElMessage.success('下载成功');
        } catch (error) {
          console.error('下载失败:', error);
          ElMessage.error('下载失败，请重试');
        } finally {
          pdf.downloading = false;
        }
      }
    };

    // 退出登录
    const handleLogout = () => {
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('username');
      localStorage.removeItem('userRole');
      localStorage.removeItem('token');
      router.push('/login');
    };

    onMounted(() => {
      username.value = localStorage.getItem('username') || '用户';
      fetchPdfList();
    });

    return {
      username,
      pdfList,
      currentPdf,
      qaList,
      hasChanges,
      loading,
      selectPdf,
      currentPage,
      currentQa,
      approveQa,
      rejectQa,
      saveAllChanges,
      handleLogout,
      downloadPdf,
      cancelApprove,
      cancelReject,
      getStatusType,
      editQa,
      confirmEdit,
      cancelEdit
    };
  }
};
</script>

<style scoped>
.a3-container {
  width: 100%;
  min-width: 1200px;
  padding: 20px;
  box-sizing: border-box;
}

.main-content {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.main-content.full-width {
  display: block;
}

.section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pdf-section {
  flex: 1;
  max-width: 400px;
  transition: all 0.3s ease;
}

.pdf-section.full-width {
  max-width: none;
}

.qa-section {
  flex: 2;
}

/* PDF列表样式 */
.pdf-list {
  margin-top: 20px;
}

.pdf-item {
  padding: 15px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.3s;
}

.pdf-item:hover {
  background-color: #f5f7fa;
}

.pdf-item.active {
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.pdf-info {
  flex: 1;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.pdf-name {
  font-weight: bold;
  color: #303133;
}

.pdf-time {
  font-size: 12px;
  color: #909399;
}

.pdf-actions {
  margin-left: 16px;
}

/* 问答对样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.qa-item {
  border: 1px solid #eaeaea;
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 20px;
  transition: all 0.3s;
}

.qa-item-approved {
  border-color: #67C23A;
  background-color: #f0f9eb;
}

.qa-item-rejected {
  border-color: #F56C6C;
  background-color: #fef0f0;
}

.qa-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.qa-index {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: bold;
  color: #409EFF;
}

.qa-status {
  display: flex;
  align-items: center;
  gap: 5px;
}

.qa-content {
  margin-top: 15px;
}

.qa-field {
  margin-bottom: 15px;
}

.qa-field label {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 8px;
  color: #606266;
  font-weight: bold;
}

.qa-text {
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 24px;
  white-space: pre-wrap;
}

.qa-actions {
  margin-top: 15px;
}

.qa-edit-actions {
  display: flex;
  gap: 10px;
}

.qa-review-actions {
  display: flex;
  gap: 10px;
}

.qa-feedback {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
}

.qa-feedback label {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #F56C6C;
  font-weight: bold;
  margin-bottom: 5px;
}

.feedback-text {
  color: #F56C6C;
  font-size: 14px;
  line-height: 1.5;
}

/* 按钮样式 */
.edit-btn {
  background-color: #409EFF;
  color: white;
}

.delete-btn {
  background-color: #F56C6C;
  color: white;
}

.confirm-btn {
  background-color: #67C23A;
  color: white;
}

.cancel-btn {
  background-color: #909399;
  color: white;
}

.save-btn {
  background-color: #409EFF;
  color: white;
  padding: 8px 16px;
}

.save-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

button {
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

button:hover:not(:disabled) {
  opacity: 0.8;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

/* 保持原有的header样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.header h1 {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #409EFF;
}

.header h1 .el-icon {
  font-size: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-info .el-icon {
  font-size: 18px;
  color: #409EFF;
}

.welcome {
  font-size: 16px;
  color: #606266;
}

.username {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
  margin: 0 10px;
}

.logout-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
}

.logout-btn:hover {
  background-color: #e64242;
}

.qa-navigation {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.qa-counter {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.qa-navigation-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.qa-item {
  margin: 0 auto;
  max-width: 800px;
}

.qa-actions .el-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.qa-navigation-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pdf-actions .el-button {
  display: flex;
  align-items: center;
  gap: 5px;
}
</style> 